import type { IPluginContext } from '@tarojs/service';
import type Config from 'webpack-chain';
import getHostPkgAlias from './getHostPkgAlias';
import path from 'path';

// const hostPkgAlias = [['', '']];

export default (
  ctx: IPluginContext,
  pluginOpts?: { linaria: boolean; host: boolean },
) => {
  const hostPkgAlias = getHostPkgAlias(
    path.resolve(ctx.paths.appPath, '..', '..'),
  ).filter(([pkgName]) => pkgName);

  ctx.modifyWebpackChain(({ chain }: { chain: Config }) => {
    chain.merge({
      optimization: {
        // 开发模式下开启 Tree Shaking
        sideEffects: true,
      },
    });

    if (pluginOpts?.linaria) {
      // linaria/loader 选项详见 https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md#webpack
      chain.module
        .rule('script')
        .use('linariaLoader')
        .loader('@linaria/webpack-loader')
        .options({
          sourceMap: process.env.NODE_ENV !== 'production',
        });
    }

    if (pluginOpts?.host) {
      hostPkgAlias.forEach(([pkgName, pkgPath]) => {
        let srcModule: any;
        const srcPath = path.join(pkgPath, 'src');

        try {
          srcModule = require(srcPath);
        } catch (err: any) {
          if (err.code !== 'MODULE_NOT_FOUND') {
            srcModule = true;
          }
        }

        // use src path instead of main field in package.json if exists
        if (srcModule) {
          // exclude es & lib folder
          if (!chain.resolve.alias.has(`${pkgName}/es`)) {
            chain.resolve.alias.set(`${pkgName}/es`, srcPath);
          }

          if (!chain.resolve.alias.has(`${pkgName}/lib`)) {
            chain.resolve.alias.set(`${pkgName}/lib`, srcPath);
          }

          if (!chain.resolve.alias.has(pkgName)) {
            chain.resolve.alias.set(`${pkgName}/src`, srcPath);
            chain.resolve.alias.set(pkgName, srcPath);
          }
        } else if (!chain.resolve.alias.has(pkgName)) {
          chain.resolve.alias.set(pkgName, pkgPath);
        }
      });
    }
  });
};
